;
(function (window, angular) {
    'use strict';
    angular.module("Controller.BasicData.SetMaterielPrice", [])
        .controller("SetMaterielPriceCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "EventBus", "UserContextService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, EventBus, UserContextService) {
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.markInfo = {
                curRow: 0
            };
            $scope.condition = {};
            $scope.dataList = [];
            $scope.priceSchemeList = [];
            $scope.materielClass = {};
            $scope.exportParam = {
                allUrl: ybHttp.RequestUrl("device", "/marketingActivity/exportAll")
            };
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.tbConf = {
                scrollWidth: 680,
                tableCol: [
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件分类",
                        dataField: "materialsType",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: $scope.isWJ ? "进货基准价" : "销售价",
                        dataField: "price",
                        width: 100,
                        isShow: true,//edit by lqx
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "已签批",
                        dataField: "signStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "designationPrice",
                        name: "指定价格方案",
                        dataField: "",
                        width: 250,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "discountPrice",
                        name: "折扣价格方案",
                        dataField: "",
                        width: 400,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            // 显示成本价
            $scope.showCostClick = function() {
                $scope.costPriceShow = !$scope.costPriceShow;
                if ($scope.costPriceShow) {
                    $scope.tbConf = {
                        scrollWidth: 900,
                        tableCol: [
                            {
                                type: "",
                                name: "零件编号",
                                dataField: "materialsNo",
                                width: 150,
                                isShow: true,
                                isFixed: false,
                                toSort: false,
                                sortType: ""
                            },
                            {
                                type: "",
                                name: "零件中文名",
                                dataField: "materialsDes",
                                width: 150,
                                isShow: true,
                                isFixed: false,
                                toSort: false,
                                sortType: ""
                            },
                            {
                                type: "",
                                name: "零件分类",
                                dataField: "materialsType",
                                width: 120,
                                isShow: true,
                                isFixed: false,
                                toSort: false,
                                sortType: ""
                            },
                            {
                                type: "",
                                name: $scope.isWJ ? "进货基准价" : "销售价",
                                dataField: "price",
                                width: 100,
                                isShow: true,
                                isFixed: false,
                                toSort: false,
                                sortType: ""
                            },
                            {
                                type: "",
                                name: "标准价",
                                dataField: "standardPrice",
                                width: 100,
                                isShow: true,
                                isFixed: false,
                                toSort: false,
                                sortType: ""
                            },
                            {
                                type: "designationPrice",
                                name: "指定价格方案",
                                dataField: "",
                                width: 250,
                                isShow: true,
                                isFixed: false,
                                toSort: false,
                                sortType: ""
                            },
                            {
                                type: "discountPrice",
                                name: "折扣价格方案",
                                dataField: "",
                                width: 400,
                                isShow: true,
                                isFixed: false,
                                toSort: false,
                                sortType: ""
                            }
                        ]
                    };
                } else {
                    $scope.tbConf = {
                        scrollWidth: 900,
                        tableCol: [
                            {
                                type: "",
                                name: "零件编号",
                                dataField: "materialsNo",
                                width: 150,
                                isShow: true,
                                isFixed: false,
                                toSort: false,
                                sortType: ""
                            },
                            {
                                type: "",
                                name: "零件中文名",
                                dataField: "materialsDes",
                                width: 150,
                                isShow: true,
                                isFixed: false,
                                toSort: false,
                                sortType: ""
                            },
                            {
                                type: "",
                                name: "零件分类",
                                dataField: "materialsType",
                                width: 120,
                                isShow: true,
                                isFixed: false,
                                toSort: false,
                                sortType: ""
                            },
                            {
                                type: "",
                                name: $scope.isWJ ? "进货基准价" : "销售价",
                                dataField: "price",
                                width: 100,
                                isShow: true,
                                isFixed: false,
                                toSort: false,
                                sortType: ""
                            },
                            {
                                type: "designationPrice",
                                name: "指定价格方案",
                                dataField: "",
                                width: 250,
                                isShow: true,
                                isFixed: false,
                                toSort: false,
                                sortType: ""
                            },
                            {
                                type: "discountPrice",
                                name: "折扣价格方案",
                                dataField: "",
                                width: 400,
                                isShow: true,
                                isFixed: false,
                                toSort: false,
                                sortType: ""
                            }
                        ]
                    };
                }
            };

            $scope.toggleUnablePrice = function (flag) {
                let priceSchemes = [];
                if (flag) {
                    priceSchemes = angular.copy($scope.priceSchemeListOri)
                } else {
                    priceSchemes = $scope.priceSchemeListOri.filter(r => r.state === 1);
                }
                $scope.priceSchemeList = priceSchemes;

                adjustMaterialsList();
            };

            $scope.fixedPrice = [];
            $scope.ratePrice = [];
            $scope.btnEnabled = true;
            $scope.materialsTypeList = [];

            var btnPermissionCode = {
                priceSchemeSetMateriel: window.ActionCode.priceSchemeSetMateriel,
                priceSchemeSetMaterielExport: window.ActionCode.priceSchemeSetMaterielExport,
                priceSchemeRemoveCache: window.ActionCode.priceSchemeRemoveCache,
                setMaterielPriceshowCostPrice: window.ActionCode.setMaterielPriceshowCostPrice,
                hideUnit: window.ActionCode.hideUnit
            };

            $scope.btnPermission = {
                priceSchemeSetMateriel: true,
                priceSchemeSetMaterielExport: true,
                priceSchemeRemoveCache: true,
                setMaterielPriceshowCostPrice: true,
                hideUnit: true
                
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            function getMaterialsType() {
                var service= "device";
                var reqUrl= "/dataDictionary/searchList";
                var param= {
                    parentCode: 'MATTYPE'
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.materialsTypeList = resp.value;
                });
            }
            
            function getPriceScheme() {
                var service = "device";
                var reqUrl = "/marketingActivity/list";
                var param = {isAllMaterials: 0,isSapFlag: true,isSetFlag: true};
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    $scope.priceSchemeListOri = angular.copy(resp.value);
                    $scope.toggleUnablePrice(false);
                });
            }

            function adjustMaterialsList() {
                angular.forEach($scope.dataList, function (item) {
                    var ratePrice = [];
                    var fixedPrice = [];
                    var activityList = item.marketingMaterialsList;
                    angular.forEach($scope.priceSchemeList, function (schemeItem) { 
                        schemeItem.checked = false;  
                        if (schemeItem.modeType === 0) {
                            ratePrice.push(schemeItem); 
                        }
                        if (schemeItem.modeType === 1) {
                            schemeItem.price = null;
                            fixedPrice.push(schemeItem);
                        }
                        for (var i = 0, len = activityList.length; i < len; i++) { 
                            var activityId = activityList[i].activityId;
                            var price = activityList[i].price;
                            if (schemeItem.id === activityId) {
                                schemeItem.checked = true;
                                schemeItem.price = !!price ? price : null;
                                break;
                            }
                        }
                    });
                    item.ratePrice = angular.copy(ratePrice);
                    item.fixedPrice = angular.copy(fixedPrice);
                });
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allChecked: false,
                    curRow: 0
                };
                var service = "device";
                var reqUrl = "/marketingActivity/marketingMaterialsList";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.dataList = resp.value.list;
                    adjustMaterialsList();
                    // 循环拿取折扣价格方案对应的价格
                    $scope.dataList.forEach(item => {
                        item.marketingActivityPriceVOList.forEach(ele => {
                            item.ratePrice.forEach(i => {
                                if (ele.activityId == i.id) {
                                    i.discountPrice = ele.discountPrice || undefined
                                }
                            });
                            item.fixedPrice.forEach(i => {
                                if (ele.activityId == i.id) {
                                    i.discountPrice = ele.discountPrice || undefined
                                }
                            });
                        });
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    // 复选框数据 拿取对应的marketingMaterialsList 值 判断是否为应用所有的零件 如果为true 就禁用
                    $scope.dataList.forEach(item => {
                        item.signStatusShow = $filter("TrueOrFalse")(item.signStatus);
                        item.ratePrice.forEach(ele => {
                            let arr = []
                            arr = item.marketingMaterialsList.filter(i => i.activityId == ele.id)
                            ele.allMaterialFlag = arr[0]?.allMaterialFlag
                        });
                    });
                });
            }
            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };
            
            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.selectScheme = function() {
                $scope.btnEnabled = false;
            };

            $scope.saveData = function () {
                var mList = [];
                angular.forEach($scope.dataList, function(item){
                    var materialsItem = {};
                    materialsItem.materialsNo = item.materialsNo;
                    materialsItem.materialsList = [];
                    item.ratePrice = item.ratePrice.filter(item => item.allMaterialFlag != true)
                    angular.forEach(item.fixedPrice, function(priceObj){
                        var curItem = {};
                        curItem.activityId = priceObj.id;
                        if (!!priceObj.price) {
                            curItem.price = priceObj.price;
                            curItem.checked = true;
                        } else {
                            curItem.checked = false;
                        }
                        materialsItem.materialsList.push(curItem);
                    });
                    angular.forEach(item.ratePrice, function(priceObj){
                        var curItem = {};
                        curItem.activityId = priceObj.id;
                        curItem.checked = priceObj.checked;
                        materialsItem.materialsList.push(curItem);
                    });
                    mList.push(materialsItem);
                });

                var service = "device";
                var reqUrl = "/marketingActivity/saveMarketingMaterials";
                ybHttp.Post(service, reqUrl, mList).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                });
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.removeCache = function () {
                var service = "device";
                var reqUrl = "/cache/remove/MARKET_MATERIALS";

                ybWidget.ShowMessage("确定要清除导出缓存吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                    });
                });
            };

            $scope.importData = function () {
                var param = {
                    name: "已签批零件",
                    templateReqService: "device",
                    templateReqUrl: "/downloadFile/excelTemplate?excelFileName=ImportMaterialSignStatus.xls",
                    importReqService: "device",
                    importReqUrl: "/materials/importSignStatus",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };

            (function () {
                getMaterialsType();
                getPriceScheme();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);